
#########################################################################

# Copyright (C) Flavio Piccinelli 2012 <flavio.picci@gmail.com>

#########################################################################

# MySqLite.rb
# This file is part of "AriaAperta".

# AriaAperta is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.

# AriaAperta is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with AriaAperta.  If not, see <http://www.gnu.org/licenses/>.

#########################################################################
#########################################################################


#########################################################################
# Required libraries
#########################################################################
require "sequel"
require "lib/const"
#########################################################################

module MySqLite

	def set_db(db_name)
		db = Sequel.sqlite("#{DB_PATH}#{db_name}")
		return db
	end

	def get_vm_id()

		db = set_db("one.db")
		begin
			vm_id_arr = db[:pool_control].filter(:tablename=>'vm_pool').map(:last_oid)
		rescue => error
			puts "exception error: #{error}, retrying in 1 sec"
			sleep 1
			retry
		end

		return vm_id_arr[0].to_s.to_i
	end


	def add_user(username, passwd, uid)#, cert_string)
		db = set_db("users.db")
		begin
			db.create_table?(:users){
				Integer :uid
				String :username
				String :passwd
				Integer :ack
# 				Text :cert
			}
			puts uid
			db[:users].insert(:uid => uid, :username => username, :passwd => passwd)#, :cert => cert_string)
		rescue => error
			puts "exception error: #{error}, retrying in 1 sec"
			sleep 1
			retry
		end
	end

	def get_users
		db = set_db("users.db")
		certs = db[:users].select_map([:username, :passwd, :ack])
		return certs
	end

	def update_ack(username, time)
		db = set_db("users.db")
		db[:users].filter(:username => username).update(:ack => time)
	end

end
